from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.views import APIView

from Admin.models import RemoteProblem
from Admin.serializers.RemoteProblem import RemoteProblemSerializer
from Admin.tasks import get_cf_problems, get_hdu_problems
from Person.authenticate import MyJSONWebTokenAuthentication
from Robots.models import RemoteOJ
from Utils.BasePageNumberPagination import MyBasePageNumberPagination
from Utils.BaseResponse import BaseResponse


class RemoteProblemGenericAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
    queryset = RemoteProblem.objects.all().order_by('-id')
    serializer_class = RemoteProblemSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated, IsAdminUser]
    filter_backends = [DjangoFilterBackend, ]
    filterset_fields = ['id', 'remote_oj']
    pagination_class = MyBasePageNumberPagination  # 使用分页器

    def get(self, request, format=None):
        res = self.list(request)
        if res.status_code == 200:
            return BaseResponse(data=res.data, status=status.HTTP_200_OK).success()
        return BaseResponse(data=res.data, status=status.HTTP_400_BAD_REQUEST).fail()

    def post(self, request, format=None):
        res = self.create(request)
        if res.status_code == status.HTTP_201_CREATED:
            return BaseResponse(data=res.data, status=status.HTTP_201_CREATED).success()
        return BaseResponse(data=res.data, status=status.HTTP_400_BAD_REQUEST).fail()


class AdminGetRemoteProblem(APIView):
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated, IsAdminUser]

    def post(self, request):
        remote_oj_id = request.data.get('remote_oj_id')
        remote_oj = RemoteOJ.objects.get(id=remote_oj_id)
        if remote_oj.name == "CF":
            task_id = get_cf_problems.apply_async().id
        elif remote_oj.name == "HDU":
            task_id = get_hdu_problems.apply_async().id
        else:
            return BaseResponse(status=status.HTTP_400_BAD_REQUEST).fail("OJ名称错误")

        return BaseResponse(data={"task": task_id}, status=status.HTTP_200_OK).success()
